var GalleryItem = new Class({
  initialize: function(gallery_item){
   var add  = new Request({url:'/partnerships', method:'post', });
   var del  = new Request({url:'/partnerships/destroy_by_item'});
   var auth = $('form_authenticity_token').value;
    
   gallery_id = $('gallery_id').value;
    
    if(paginator =  gallery_item.getElement('.pagination')){
      var paging       =  new Request.HTML({method:'get',
          onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript){
          gallery_item.empty();
          gallery_item.set('html', responseHTML);
        },
      });
    };
        
    gallery_item.addEvent('click', function(event){
      var parent = $(event.target).getParent('table')
      if(parent.hasClass("photo") && parent.hasClass('clickable')){
        item_id = $(event.target).getElement('.item_id').value
        if(parent.hasClass("partnered")){
          id = parent.getElement('.partnership_id')
          //parent.addClass('ajax-loading');
          del.send(new Hash({'partnership[item_id]':item_id, item_type:'photo', 'partnership[gallery_id]':gallery_id, authenticity_token:auth}).toQueryString())
        } else {
          //parent.addClass('ajax-loading');
          add.send(new Hash({'partnership[photo_id]':item_id, item_type:'photo', 'partnership[gallery_id]':gallery_id, authenticity_token:auth}).toQueryString())
        }
        parent.toggleClass('partnered')
      }
      
      else if(event.target.hasClass("video") && parent.hasClass('clickable')){
        var item_id = $(event.target).getElement('.item_id').value
        if(parent.hasClass("partnered")){
          id = parent.getElement('.partnership_id')
          del.send(new Hash({'partnership[item_id]':item_id, item_type:'video', 'partnership[gallery_id]':gallery_id, authenticity_token:auth}).toQueryString())
        } else {
          add.send(new Hash({'partnership[video_id]':item_id, item_type:'video', 'partnership[gallery_id]':gallery_id, authenticity_token:auth}).toQueryString())
        }
        parent.toggleClass('partnered')
      }
      
      else if(event.target.parentNode.hasClass('pagination') && event.target.get('tag') == 'a'){
        event.stop();
        paging.options['url'] = event.target.href
        paging.send(new Hash({gallery_id:gallery_id}).toQueryString())
      }
    })
  },
  
});
window.addEvent('domready', function(){
 $$('.gallery_items').each(function(gallery_item){
   new GalleryItem(gallery_item);
 })
});